package pl.edu.agh.idrd.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

public class HibernateDAO<T> {
	
	private Class clazz;

	public HibernateDAO(Class clazz) {
		this.clazz = clazz;
	}

	public void persist(T obj) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		session.saveOrUpdate(obj);
		session.getTransaction().commit();
		session.close();
	}

	public void delete(T obj) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		session.delete(obj);
		session.getTransaction().commit();
		session.close();
	}

	public void update(T obj) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		session.update(obj);
		session.getTransaction().commit();
		session.close();
	}

	public List<T> get() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		List<T> resultList = session.createQuery("from " + clazz.getName()).setFirstResult(1).setMaxResults(10000)
				.list();
		session.getTransaction().commit();
		session.close();
		return resultList;
	}

	public List<T> get(String query) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();		
		Query q = session.createQuery(
				"from " + clazz.getName() + " " + query);
		q.setMaxResults(10000);		
		List<T> resultList = q.list();
		session.getTransaction().commit();
		session.close();
		return resultList;
	}
}
